import React, { useCallback, useEffect, useRef, useState } from "react";
import styles from "./xx-goodsMainPciture.module.scss";
import { Image, message, } from "antd";
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons';
import { downloadFileFromOSS, upFileToOSS } from '@/ui/xx-AliyunOSSUpload/client/AliOss';
import { uuid } from '@/utils';



/**
 * @description 仿淘宝商品发布 多图片切换展示，适用于商品编辑 多图缩略，主图展示
 * 
 */
const XxMultipleImage = ({
    style = Object,
    onChange,
    value,
    accept = 'image/png,image/jpg,image/jpeg',
    maxCount = 5,
    multiple = true,
    mainImageStyles = {
        height: 350,
        width: 350,
        overflow: "hidden"
    },
    warpStyle = {}
}) => {
    const [curObj, setCurObj] = useState(null);
    const [loading, setLoading] = useState(false);
    const [fileList, setFileList] = useState([]);

    // 原生上传组件
    const useCustUpload = async (e) => {
        try {
            setLoading(true);
            let file = e.target.files[0]
            let metaData = {
                fileName: file.name,
                busiId: `contractEntity.contractCode`,
                busiType: 'OBC'
            }
            let res = await upFileToOSS(file, metaData);
            if (res.url) {
                console.log("上传成功", res)
                let metaData = {
                    fileName: res.name,
                    busiId: `contractEntity.contractCode`,
                    busiType: 'OBC'
                }
                let imgUrl = await downloadFileFromOSS(metaData)
                if (imgUrl.status === "0000") {
                    setFileList([...fileList, {
                        url: imgUrl?.data?.url,
                        uid: uuid(),
                        name: res.name
                    }])
                    setCurObj({
                        url: imgUrl?.data?.url,
                        uid: uuid(),
                        name: res.name
                    })
                } else {
                    message.error("图片加载失败")
                }

            } else {
                message.error("图片上传失败：")
                onError()
            }
        } catch (error) {
            message.error("网络连接失败")
        } finally {
            setLoading(false);
        }
    }




    const uploadButton = (
        <button
            style={{
                border: 0,
                background: 'none',
            }}
            type="button"
        >
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
        </button>
    );


    const inputRef = useRef(null);
    const handleDivClick = useCallback(() => {
        inputRef.current.click();
    }, []);




    // 删除图片
    const onDeleteImage = (object) => {
        const deleteIndex = fileList.findIndex(obj => object.url === obj.url);
        let tempFileList = [];
        tempFileList = fileList.filter(item => item.url !== object.url);
        if (deleteIndex === 0) {
            // 如果删除的是最前面的项
            setCurObj(tempFileList[0]);
        } else if (deleteIndex === fileList.length - 1) {
            // 如果删除的是最后一项
            setCurObj(tempFileList[deleteIndex - 1]);
        } else {
            setCurObj(tempFileList[deleteIndex]);
        }
        setFileList(tempFileList);
    }


    // 设置为主图 设为封面，就把图片放最前面来
    const setCoverImage = (object) => {

        let tempFileList = [];
        tempFileList = fileList.filter(item => item.url !== object.url)
        tempFileList.unshift(object);
        console.log("新的图片顺序：", tempFileList)
        setFileList(tempFileList);
    }

    useEffect(() => {
        fileList.length > 0 ? setCurObj(fileList[0]) : null
    }, [])

    return (
        <div className={styles.box} style={{ ...style }}>
            <div className="center">
                <div className="mainImageSpace">
                    {
                        curObj ? (
                            <>
                                <Image
                                    className="mainImage"
                                    preview={false}
                                    width={mainImageStyles.width}
                                    height={mainImageStyles.height}
                                    style={{ ...mainImageStyles }}
                                    src={`${curObj.url}`}
                                />
                                <div className="action">
                                    <span className="btn" onClick={() => setCoverImage(curObj)}>设为主图</span>
                                    <span className="btn" onClick={() => onDeleteImage(curObj)}>删除</span>
                                </div>
                            </>
                        )
                            :
                            <div className="empty"
                                style={{
                                    height: mainImageStyles.height,
                                    width: mainImageStyles.width,

                                }}
                            >
                                暂未上传图片
                            </div>
                    }

                </div>
                {/* 缩略小图 */}
                <div className="breviarySpace">
                    {
                        fileList.map((item, index) => {
                            return (
                                <div
                                    className="breviarySpace-item"
                                    key={index}>
                                    <div className="item-center"

                                    >
                                        <Image
                                            onClick={() => setCurObj({
                                                url: item.url,
                                                uid: uuid(),
                                                name: item.name,
                                                index: index
                                            })}
                                            preview={false}
                                            width={46}
                                            height={46}
                                            src={`${item.url}`}

                                        />
                                    </div>
                                </div>
                            )
                        })
                    }
                    {/* 自己封装的上传 */}
                    {
                        fileList.length >= maxCount ?
                            null : (
                                <div className="breviarySpace-item upload-use"
                                    onClick={handleDivClick}
                                >
                                    <input
                                        ref={inputRef}
                                        style={{ display: "none" }}
                                        className="input-hide"
                                        type="file"
                                        onChange={useCustUpload}
                                        accept={accept}

                                    />
                                    <div className="item-center"
                                    >
                                        {
                                            fileList.length >= maxCount ? (
                                                null
                                            ) : (
                                                uploadButton
                                            )}
                                    </div>

                                </div>
                            )
                    }
                </div>
            </div>
        </div>
    )
}
export default XxMultipleImage